package com.example.interceptor;

import com.example.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Auther: Sun
 * @Date: 2025/9/24 - 09 - 24 - 16:26
 * @Description: com.example.interceptor
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String request1 = request.getRequestURI();
        if (request1.contains("/login")) {
            log.info("登陆操作");
            return true;
        }
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.info("令牌为空,响应401状态码");
            response.setStatus(401);
            response.getWriter().write("用户未登录，请先登录");
            return false;
        }
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            log.info("令牌非法,响应401状态码");
            response.setStatus(401);
            return false;
        }
        log.info("令牌合法,放行");
        return true;
    }
}

